<template>
  <div style="">
    <div class="bp-title">
      微信登录成功请绑定手机号
    </div>
    <div class="bp-input">
      <div class="div-input">
        <input type="text" v-model="phone" placeholder="请输入手机号" style="min-width:300px">
      </div>
      <div class="div-input">
        <input type="text" v-model="code" placeholder="请输入验证码">
        <van-button v-if="!isDisable" class="bp-btn" plain size="small" :disabled="isDisable" @click="getCode">
          {{codeMsg}}</van-button>
        <div v-else class="bp-btn fake-btn">{{codeMsg}}</div>
      </div>
    </div>
    <van-button :disabled="isBindDisable" loading-text="确认绑定" class="check-button" @click="bindPhone">{{'确认绑定'}}
    </van-button>

    <!-- 弹窗 v-model="isLoading"-->
    <van-dialog v-model="isBindDialog" @confirm="confirm" @cancel="cancel" title="此手机号已绑定其他微信号" show-cancel-button
      confirm-button-color="#169bd5">
      <div class="dialog-content">
        如继续绑定此微信，原微信号将被解绑！是否继续绑定此微信号？
      </div>
    </van-dialog>

    <!-- 弹出选择 -->
    <van-overlay :show="isLoading" @click="overlayFunc">
      <div class="pop-content">
        <div class="pop-title">
          发现您在一览有两个账号，您希望继续保留使用哪个账号？
        </div>
        <div class="pop-tips">选择后，微信号与手机号将关联到同一账号中，但简历、投递、面试记录、订单、资产将不会转移，请您留意。若您已参与适岗培训，请选择手机号为账号主体。</div>
        <div class="pop-joblist">
          <van-radio-group v-model="radioIndex">
            <!-- <van-radio class="job-radio" name="0" checked-color="#F04646">
              <div>
                <div class="job-name">乔秀英</div>
                <div class="job-tags">
                  <span>23次投递</span>
                  <span>10次面试</span>
                  <span>10次面试</span>
                  <span>0余额</span>
                </div>
                <div class="job-history">
                  <span>2001年注册</span>
                  <span>手机号关联账户</span>
                </div>
              </div>
              <div><img src="" alt=""></div>
              <van-image class="job-img" round width="32px" height="32px" src="https://img.yzcdn.cn/vant/cat.jpeg" />
              <div class="job-resume">
                完善度：85%
              </div>
            </van-radio>
            <van-radio class="job-radio" name="1" checked-color="#F04646">
              <div>
                <div class="job-name">乔秀英1</div>
                <div class="job-tags">
                  <span>23次投递</span>
                  <span>10次面试</span>
                  <span>10次面试</span>
                  <span>0余额</span>
                </div>
                <div class="job-history">
                  <span>2001年注册</span>
                  <span>手机号关联账户</span>
                </div>
              </div>
              <div><img src="" alt=""></div>
              <van-image class="job-img" round width="32px" height="32px" src="https://img.yzcdn.cn/vant/cat.jpeg" />
              <div class="job-resume">
                完善度：85%
              </div>
            </van-radio> -->
    
            <van-radio class="job-radio" :name="item.check_value" checked-color="#F04646" v-for="(item,index) in accountList" :key="index">
              <div>
                <div class="job-name">{{item.iname||item.id}}</div>
                <div class="job-tags">
                  <span>{{item.cmail_box_count}}次投递</span>
                  <span>{{item.mianshi_tz_cnt}}次面试</span>
                  <span>{{item.lesson}}课程</span>
                  <span>{{item.total_balance}}余额</span>
                </div>
                <div class="job-history">
                  <span>注册:{{item.regtime}}</span>
                  <span>{{item.type_desc}}</span>
                </div>
              </div>
              <div><img src="" alt=""></div>
              <van-image class="job-img" round width="32px" height="32px" :src="item.pic" />
              <div class="job-resume">
                完善度{{item.percentage||0}}%
              </div>
            </van-radio>

          </van-radio-group>
        </div>
        <van-button class="pop-btn save-btn" :disabled="isJobSave" loading-text="保留此账号登录一览" @click="handleJobSave">保留此账号登录一览</van-button>
        <van-button class="pop-btn nochoice-btn" @click="handleJobCancel">暂不选择，维持两个账号</van-button>
      </div>
    </van-overlay>

    <!-- 渲染一个隐藏文件 -->
    <div v-html="fakeDoc"></div>
  </div>
</template>

<script>
  let timer;
  import handle from '@/utils/handle.js';

  export default {
    data() {
      return {
        isDisable: false,
        codeMsg: '发送验证码',
        isBindDisable: true,
        isLoading: false,
        isBindDialog:false,
        // isAllExist:false,
        phone: '',//'15814691183',//先默认写死
        code: '',//'572561',
        radioIndex: 1, //对应radio name的标识符
        bindPhoneData:{},
        accountList:[],//两个账号列表
        fakeDoc:'',
        isJobSave:false
      }
    },
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不！能！获取组件实例 `this`
    // 因为当守卫执行前，组件实例还没被创建
    beforeRouteEnter (to, from, next) {
      console.log('beforeRouteEnter',to,from,next);
      next((vm)=>{
        console.log(vm.$router);
      })
      
    },
    created () {
      // alert(this.bindPhoneData.mobile_person)
      // this.thirdChoosePerson('19587560').then(res=>{
      //   console.log(res);
      //   debugger
      // });
    },
   
    computed: {
      cj_id(){//抽奖
        return this.$route.query["cj_id"];
      },
      liveId() {
        return this.$route.query["live_id"];
      },
      unionid() {
        let id;
        if(localStorage.getItem("unionid")==null||localStorage.getItem("unionid")==undefined||localStorage.getItem("unionid")==''){
          id=localStorage.getItem('openid')
        }else{
          id=localStorage.getItem("unionid")
        }
        return this.$route.query.unionid || id
      },
      isAllExist() {
        let { phone, code} = this
        return {phone,code}
      }
    },
    watch: {
      isAllExist() {
        if (handle.checkPhone(this.phone) && this.code) {
          this.isBindDisable = false
        } else {
          this.isBindDisable = true
        }
      }
    },
    methods: {
      setCodeInterval() {
        //设置验证码重新发送定时器
        let time = 60;
        clearInterval(timer);
        timer = setInterval(() => {
          time--;
          this.isDisable = true,
            this.codeMsg = `重新发送(${time}s)`

          if (time <= 0) {
            this.isDisable = false,
              this.codeMsg = '重新发送'
            clearInterval(timer);
          }
        }, 1000)
      },
      clearCodeInterval() {
        clearInterval(timer);
        this.codeMsg = '获取验证码'
      },

      getCode() {
        if (!handle.checkPhone(this.phone)) {
          return this.$toast('请输入正确手机号')
        }
        this.sendMsgCode().then(res=>{
          this.$toast(res.data.status_desc)//提示
          if(res.data.code==200){
            //倒计时
            this.setCodeInterval()
          }else if(res.data.code==1001){
            this.phone=''
          }else if(res.data.code==1060){
             this.$router.replace({
              name: "login",
              query: {
                cj_id: this.cj_id,
              },
            });
          }
        })
      },

      /**1.绑定成功调到直播页面
       * 2.绑定其他手机时,弹窗提示,用户做出选择
       * 3.检查出两个账号时, 弹出选择的账号,然后在会跳到直播页面
       *  */
      bindPhone() {
        //TODO绑定手机的接口
        // 4030 手机号已有关联账号 跳选择账号界面 ；4040 手机号已绑定过第三方(微信) 跳确认是否解绑界面；4045 第三方(微信) 授权失效需要重新授权；140 验证码错误；
        //data中: {"mobile_person":"111",//手机号关联的账号"is_new_person":"1"//是新用户 新,走thirdChoosePerson}
        // this.isLoading = true
        // this.goLive()
        // let unionid='oqZiBjkFuiL5bjvjje-qcfH-tP90';
        this.isDisable=true
        this.bindMoblie().then(res=>{
          this.$toast(res.data.status_desc)
          if(res.data.status=='OK'){
            handle.clearAllCookie()//清除cookie
            this.loginOut() //清除session
            setTimeout(()=>{
              this.goLive()
            },1000)
            
            
          }
          else if(res.data.code==200){
            this.loginOut() //清除session
            setTimeout(()=>{
              this.goLive()
            },1000)
          }else if(res.data.code==4001){//登录失效
            this.$router.replace({
              name: "login",
              query: {
                cj_id: this.cj_id,
              },
            });
          }
          else if(res.data.code==4030){
            this.bindPhoneData=res.data.data //这个用bindPhoneData存储下面4040也是
            let mobile_person=res.data.data.mobile_person
            this.getChoosePersonInfo(mobile_person).then(res=>{//获取两个账号的信息
              if(res.data.code==200){
                this.isLoading=true //弹出选择账号
                this.accountList=res.data.data //根据check_value==1,排在第0位
                // if(this.accountList[0].check_value!==1){
                //   this.accountList.reverse()
                // }
              }else{
                this.$toast(res.data.status_desc)
                this.phone=''
                this.code=''
              }
            }).catch(err=>{

            })
            

          }else if(res.data.code==4040){
            this.bindPhoneData=res.data.data
            this.isBindDialog=true //弹出解绑

          }else if(res.data.code==4045){//微信授权失败(跳回登录页面)
            this.$router.replace({
              name: "login",
              query: {
                cj_id: this.cj_id,
              },
            });
          }else if(res.data.code==140){//验证码错误重新输入验证码
            this.code=''

          }else{

          }
        })
        this.isDisable=false
      },


      confirm() {//解绑若发现存在多个账号,弹窗,否则跳回直播
        //TODO 选择解绑的微信(接口现在好像没有), 1050 表示流程失效 要重新输入手机号验证码
        //手机存在两个账号,关闭当前,跳到另一个弹窗选择账号19587560
        // alert(this.bindPhoneData.mobile_person)
        if(this.bindPhoneData.is_new_person==1){
          this.thirdChoosePerson(this.bindPhoneData.mobile_person).then(res=>{
            this.$toast(res.data.status_desc)
            if(res.data.code==200){
              this.loginOut() //清除session
              setTimeout(()=>{
              this.goLive()
            },1000)
            }
            else if(res.data.code==1050){
              this.phone=''
              this.code=''
            }else if(res.data.code==4001){
              this.$router.replace({
                name: "login",
                query: {
                  cj_id: this.cj_id,
                },
              });
            }
            console.log(res);
          }).catch(err=>{
            console.log(err);
          })
        }else{
          this.getChoosePersonInfo(this.bindPhoneData.mobile_person).then(res=>{//获取两个账号的信息
              if(res.data.code==200){
                this.isBindDialog=false
                this.isLoading=true //弹出选择账号
                this.accountList=res.data.data
                // if(this.accountList[0].check_value!==1){
                //   this.accountList.reverse()
                // }
              }else{
                this.$toast(res.data.status_desc)
                this.phone=''
                this.code=''
              }
            }).catch(err=>{

            })
        }
      },
      cancel() {//不解绑跳回
        this.goLive()
      },
      overlayFunc(e) {
        // console.log(1111);
        // this.isLoading=false
      },
      //保留一个账号, 跳回直播页面
      handleJobSave() {
        //TODO调用接口
        let choose_person;  //=this.accountList[this.radioIndex].id
        this.accountList.map(item=>{
          if(item.check_value==this.radioIndex){
            choose_person=item.id
          }
        })
        this.isJobSave=true
        this.choosePerson(choose_person).then(res=>{
          this.$toast(res.data.status_desc)
          if(res.data.code==200){
            this.$toast({
              message: '绑定成功',
              icon: require('@/assets/success.png'),
            });
            this.loginOut() //清除session
            setTimeout(()=>{
              this.goLive()
            },1000)
          }
        }).catch(err=>{

        })
        this.isJobSave=false
        
      },
      //维持两个账号,也是跳回直播页面
      handleJobCancel() {
        this.goLive()
      },
      sendMsgCode(){ //验证码接口
        return this.$http({
          url: this.$http.adornUrl('index/user/sendMsgCode','proxyPhp'),
          method: "post",
          data:{
            mobile:this.phone,
            unionid:this.unionid
          }
        })
      },
      thirdChoosePerson(mobile_person){//新用户 微信（第三方）直接绑定手机号
        return this.$http({
          url: this.$http.adornUrl('index/user/thirdChoosePerson','proxyPhp'),
          method: "post",
          data:{
            mobile_person,
          }
        })
      },
      choosePerson(choose_person){//微信（第三方）选择绑定的账号
        return this.$http({
          url: this.$http.adornUrl('index/user/choosePerson','proxyPhp'),
          method: "post",
          data:{
            choose_person, //对应人才信息接口的id）
          }
        })
      },
      
      checkBindMobile(){//检测用户是否绑定过手机号(这个放在直播页面进行判断跳转,是否可以根据路由守卫来直接判断)
        return this.$http({
          url: this.$http.adornUrl('index/user/checkBindMobile','proxyPhp'),
          method: "post",
        })
      },
      bindMoblie(){//绑定手机号(这个unionid)
        return this.$http({
          url: this.$http.adornUrl('index/user/bindMoblie','proxyPhp'),
          method: "post",
          data:{
            authCode:this.code, 
            // unionid:this.unionid
          }
        })
      },
      getChoosePersonInfo(mobile_person){//获取2个对比账号的信息
        return this.$http({
          url: this.$http.adornUrl('index/user/getChoosePersonInfo','proxyPhp'),
          method: "get",
          params:{
            mobile_person
          }
        })
      },
      //绑定成功清除session
      loginOut(){
        this.$http({
          url: this.$http.adornUrl('index/user/loginOut','proxyPhp'),
          method: "post",
        }).then(res=>{
          console.log('文件',res);
          this.fakeDoc=res.data.data.html
        })
      },

      //跳回直播页面函数
      goLive() {
        this.$router.replace({
          name: 'show',
          query: {
            cj_id: this.cj_id,
          }
        })
      }
    },
  }

</script>

<style scoped>
  .bp-title {
    padding: 28px;
    font-size: 24px;
    color: #222222;
    line-height: 28px;
    font-weight: bold;
  }

  .bp-input {
    display: flex;
    flex-flow: column;
    padding: 28px;
    padding-bottom: 40px;
  }

  .div-input {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #E7E7E7;
  }

  input {
    border: none;
    padding: 16px;
    padding-left: 0;
    font-size: 16px;
    color: #222222;
    font-weight: bold;
  }

  input::placeholder {
    font-size: 16px;
    font-weight: normal;
    color: #BBBBBB;
    line-height: 18px;
  }

  .bp-btn {
    flex-shrink: 0;
    font-size: 14px;
    color: #F04646;
    border: none;
  }

  .fake-btn {
    font-size: 14px;
    color: #555555;
  }

  .check-button {
    width: 319px;
    height: 44px;
    line-height: 44px;
    text-align: center;
    display: block;
    margin: 0 auto;
    font-size: 16px;
    color: #FFFFFF;
    background: #F04646;
    box-shadow: 0px 5px 12px 0px rgba(255, 0, 30, 0.1);
    border-radius: 24px;
  }

  .dialog-content {
    padding: 16px;
  }


  .pop-content {
    position: absolute;
    bottom: 0;
    width: 100%;
    min-height: 500px;
    background: #FFFFFF;
    border-radius: 16px 16px 0 0;
    padding: 16px;
    box-sizing: border-box;
  }

  .pop-title {
    font-size: 16px;
    color: #222222;
    letter-spacing: 0;
    line-height: 24px;
    font-weight: bold;
  }

  .pop-tips {
    font-size: 13px;
    color: #555555;
    letter-spacing: 0;
    line-height: 20px;
    margin-top: 8px;
    margin-bottom: 24px;
  }

  .job-radio {
    background: #FFFFFF;
    box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.15);
    border-radius: 8px;
    padding: 16px 12px;
    position: relative;
    margin-bottom: 12px;
  }

  .job-name {
    font-size: 18px;
    color: #222222;
    letter-spacing: 0;
    line-height: 20px;
    font-weight: bold;
  }

  .job-tags {
    font-size: 12px;
    color: #222222;
    line-height: 12px;
    padding: 12px 0 8px 0;

  }

  .job-history {
    font-size: 12px;
    color: #888888;
    line-height: 12px;
  }

  .job-tags span {
    margin-right: 12px;
  }

  .job-history span {
    margin-right: 12px;
  }

  .job-img {
    position: absolute;
    top: 16px;
    right: 12px;
  }

  .job-resume {
    display: inline-block;
    background: #F5F5F5;
    border-radius: 16px 0 0 16px;
    font-size: 13px;
    color: #F04646;
    line-height: 12px;
    padding: 8px 12px;
    width: 104px;
    box-sizing: border-box;
    position: absolute;
    right: 0;
    bottom: 12px;

  }

  .pop-btn {
    border-radius: 8px;
    width: 100%;
  }

  .save-btn {
    margin-top: 24px;
    background: #F04646;
    font-size: 16px;
    color: #FFFFFF;
    letter-spacing: 0;
    text-align: center;
    line-height: 30px;
  }

  .nochoice-btn {
    border: none;
    font-size: 13px;
    color: #555555;
    letter-spacing: 0;
    text-align: center;
    line-height: 14px;
  }

</style>
